<?php
namespace Infinity;


class Menu {
  public static function getParents($path_or_mlid, $selected_menu='main-menu') {
    $mlid = 0;
    if(is_numeric($path_or_mlid)) {
      $mlid = $path_or_mlid;
    }else if(is_string($path_or_mlid)) {
      $menu = menu_link_get_preferred($path_or_mlid, $selected_menu);
      if(!$menu) return false;
      $mlid = $menu['mlid'];
    }

    $menu = self::getItem($mlid);
    $menus = array();
    for($i=1; $i<10 && $menu['p'.$i]; $i++) {
      $menus []= self::getItem($menu['p'.$i]);
    }
    return $menus;
  }

  public static function getChildren($mlid) {
    $or = db_or();
    for($i=1; $i<=9; $i++) {
      $or->condition('ml.p'.$i, $mlid);
    }

    $menus = db_select('menu_links', 'ml')
      ->condition($or)
      ->condition('ml.mlid', $mlid, '<>')
      ->fields('ml')
      ->execute()
      ->fetchAllAssoc('ml.mlid', \PDO::FETCH_ASSOC);
    return $menus;
  }

  public static function getItem($mlid) {
    return db_select('menu_links', 'ml')
      ->condition('ml.mlid', $mlid)
      ->fields('ml')
      ->execute()
      ->fetchAssoc();
  }

  public static function getIdByTitle($title, $selected_menu='main-menu', $parent_id=0) {
    $query = db_select('menu_links', 'ml')
      ->condition('ml.title', trim($title))
      ->condition('ml.menu_name', $selected_menu)
      ->fields('ml', array('mlid'));
    if($parent_id)
      $query->condition('ml.plid', $parent_id);
    $mlids = $query->execute()
      ->fetchCol();
    $mlid = 0;
    if($mlids)
      $mlid = array_pop($mlids);
    return $mlid;
  }
}